package com.yy.studyspringboot.poi;

import java.awt.image.BufferedImage;
import java.io.*;

import javax.imageio.ImageIO;

import cn.hutool.core.io.resource.ClassPathResource;
import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
import org.apache.poi.hssf.usermodel.HSSFPatriarch;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.ClientAnchor;

public class ExcelImageTest {
 
  public static void main(String[] args) { 
    FileOutputStream fileOut = null;   
    BufferedImage bufferImg = null;   
    //先把读进来的图片放到一个ByteArrayOutputStream中，以便产生ByteArray  
    try { 
      ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();   
//      bufferImg = ImageIO.read(new File("classpath:file/motorola.png"));
      ClassPathResource resource = new ClassPathResource("file/motorola.png");
      InputStream inputStream = resource.getStream();
      bufferImg = ImageIO.read(inputStream);

      ImageIO.write(bufferImg, "png", byteArrayOut);
       
      HSSFWorkbook wb = new HSSFWorkbook();
      //测试生成多个sheet
      HSSFSheet sheet1 = wb.createSheet("test picture");
      HSSFSheet sheet2 = wb.createSheet("test picture2");
      doContext(byteArrayOut, wb, sheet1);
      doContext(byteArrayOut, wb, sheet2);
      fileOut = new FileOutputStream("D:/测试Excel.xls");
      // 写入excel文件   
      wb.write(fileOut);   
      System.out.println("----Excle文件已生成------");
    } catch (Exception e) {
      e.printStackTrace(); 
    }finally{ 
      if(fileOut != null){ 
        try { 
          fileOut.close(); 
        } catch (IOException e) { 
          e.printStackTrace(); 
        } 
      } 
    } 
  }

  private static void doContext(ByteArrayOutputStream byteArrayOut, HSSFWorkbook wb, HSSFSheet sheet1) {
    //画图的顶级管理器，一个sheet只能获取一个（一定要注意这点）
    HSSFPatriarch patriarch = sheet1.createDrawingPatriarch();
    //anchor主要用于设置图片的属性
    HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 255, 50,(short) 0, 0, (short) 1, 1);
    anchor.setAnchorType(ClientAnchor.AnchorType.DONT_MOVE_AND_RESIZE);
    //插入图片
    patriarch.createPicture(anchor, wb.addPicture(byteArrayOut.toByteArray(), HSSFWorkbook.PICTURE_TYPE_JPEG));
  }
}